<template>
  <a-drawer
    v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 580 ? 580 : '100%'" @before-ok="save" @close="reset"
  >
    <a-form ref="formRef" :model="form" :rules="rules" size="large" auto-label-width>
      <fieldset>
        <legend>基础信息</legend>
        <a-form-item label="handle" field="handle">
          <a-input v-model.trim="form.handle" placeholder="请输入handle" />
        </a-form-item>
        <a-form-item label="标题" field="title">
          <a-input v-model.trim="form.title" placeholder="请输入handle" />
        </a-form-item>
        <a-form-item label="路径" field="path">
          <a-input v-model.trim="form.path" placeholder="请输入路径" :disabled="isUpdate" />
        </a-form-item>
        <a-form-item label="method" field="action">
          <a-select v-model="form.action" placeholder="请选择接口方法" clearable>
            <a-option>GET</a-option>
            <a-option>POST</a-option>
            <a-option>PUT</a-option>
            <a-option>DELETE</a-option>
            <a-option>PATCH</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="类型" field="type">
          <a-select v-model="form.type" placeholder="请选择类型" clearable>
            <a-option>SYS</a-option>
            <a-option>BUS</a-option>
            <a-option>暂无</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属分类" field="description">
          <a-tree-select
            v-model="form.category"
            placeholder="请选择上级菜单"
            allow-clear
            allow-search
            :data="categoryList"
            :fallback-option="false"
          />
        </a-form-item>
        <a-form-item label="描述" field="description">
          <a-textarea
            v-model.trim="form.description" placeholder="请输入描述" show-word-limit :max-length="200"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </fieldset>
      <a-alert type="warning" style="margin-bottom: 15px">
        请谨慎变更功能权限或数据权限，可能会引起系统访问权限问题！
      </a-alert>
    </a-form>
  </a-drawer>
</template>

<script setup lang="ts">
import { type FormInstance, Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { addApi, getApi, updateApi } from '@/apis/system/api'
import { useResetReactive } from '@/hooks'
import { useApiCategory } from '@/hooks/app/useApiCategory'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改系统接口' : '新增系统接口'))
const formRef = ref<FormInstance>()
const { categoryList, getCategoryTree } = useApiCategory()

const rules: FormInstance['rules'] = {
  title: [{ required: true, message: '名称不能为空' }],
  path: [{ required: true, message: '标题不能为空' }],
  action: [{ required: true, message: '接口方法不能为空' }],
  type: [{ required: true, message: '接口类型不能为空' }],
}

const [form, resetForm] = useResetReactive({
  category: '',
  handle: '',
  title: '',
  path: '',
  type: '',
  action: '',
  description: '',
})

// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

const visible = ref(false)
// 新增
const onAdd = async () => {
  reset()
  if (!categoryList.value.length) {
    await getCategoryTree()
  }

  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()

  if (!categoryList.value.length) {
    await getCategoryTree()
  }

  const res = await getApi(id)
  Object.assign(form, res.data)
  dataId.value = id
  visible.value = true
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateApi(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addApi(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

defineExpose({ onAdd, onUpdate })
</script>

<style lang="scss" scoped>
fieldset {
  padding: 15px 15px 0 15px;
  margin-bottom: 15px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

fieldset legend {
  color: rgb(var(--gray-10));
  padding: 2px 5px 2px 5px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}
</style>
